package testjvm.testclassloader02;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class SimpleURLClassLoader extends URLClassLoader {
    // 工程 class 类所在的路径
    public static String projectClassPath = "C:/Users/xxyzz/IdeaProjects/Java-Learning/06-demo/target/classes/";
    // 所有的测试的类都在同一个包下
    public static String packagePath = "testjvm/testclassloader02/";

    public SimpleURLClassLoader() {
        // 设置 ClassLoader 加载的路径
        super(getMyURLs());
    }

    private static URL[] getMyURLs() {
        URL url = null;
        try {
            url = new File(projectClassPath).toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return new URL[]{url};
    }

    public Class load(String name) throws Exception {
        return loadClass(name);
    }

    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return loadClass(name, false);
    }

    /**
     * 重写 loadClass，不采用双亲委托机制（"java."开头的类还是会由系统默认 ClassLoader 加载）
     */
    @Override
    public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class clazz = null;
        // 查看 HotSwapURLClassLoader 实例缓存下，是否已经加载过 class
        clazz = findLoadedClass(name);
        if (clazz != null) {
            if (resolve) {
                resolveClass(clazz);
            }
            return (clazz);
        }

        // 如果类的包名为 "java." 开始，则由系统默认加载器 AppClassLoader 加载
        if (name.startsWith("java.")) {
            try {
                // 得到系统默认的加载 ClassLoader，即 AppClassLoader
                ClassLoader system = ClassLoader.getSystemClassLoader();
                clazz = system.loadClass(name);
                if (clazz != null) {
                    if (resolve) resolveClass(clazz);
                    return (clazz);
                }
            } catch (ClassNotFoundException e) {
                // Ignore
            }
        }

        return customLoad(name, this);
    }

    /**
     * 自定义加载
     *
     * @param name
     * @param cl
     * @return
     * @throws ClassNotFoundException
     */
    public Class customLoad(String name, ClassLoader cl) throws ClassNotFoundException {
        return customLoad(name, false, cl);
    }

    /**
     * 自定义加载
     *
     * @param name
     * @param resolve
     * @return
     * @throws ClassNotFoundException
     */
    public Class customLoad(String name, boolean resolve, ClassLoader cl) throws ClassNotFoundException {
        // indClass() 调用的是 URLClassLoader 里面重载了 ClassLoader 的 findClass() 方法
        Class clazz = ((SimpleURLClassLoader) cl).findClass(name);
        if (resolve) ((SimpleURLClassLoader) cl).resolveClass(clazz);
        return clazz;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        return super.findClass(name);
    }
}

